//
//  SMSVerifyViewController.swift
//  todoApp
//
//  Created by Luochun on 15/5/2.
//  Copyright (c) 2015年 ll studio. All rights reserved.
//

import UIKit

protocol SMSVerifyDelegate:NSObjectProtocol {
    func verifyCompleted()
}

class SMSVerifyViewController: UIViewController {
    var delegate:SMSVerifyDelegate!
    
    var tick = 60   //倒计时
    var phone:String!
    var area:String!
//    var codeView:UIView!
//    var textField:UITextField!
//    var pwdtextField:UITextField!
    var reSendButton:UIButton!
    var tmpString:String = String()
    @IBOutlet var tishiLabel: UILabel!
    @IBOutlet var verTextfield: UITextField!
    @IBOutlet weak var verifyBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.verTextfield.backgroundColor=BACKGROUND_COLOR
        self.view.backgroundColor=BACKGROUND_COLOR
        self.verifyBtn.backgroundColor=BUTTON_COLOR
//        self.title = "验证"
//        self.view.backgroundColor = UIColor.whiteColor()
//        
//        var navigationBar:UINavigationBar = UINavigationBar(frame: CGRectMake(0, 20, self.view.frame.size.width, 44))
//        var navigationItem:UINavigationItem = UINavigationItem()
//        var leftbtn:UIBarButtonItem = UIBarButtonItem(title: "back", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("back"))
//        navigationItem.title = "验证"
//        navigationBar.pushNavigationItem(navigationItem, animated: false)
//        navigationItem.setLeftBarButtonItem(leftbtn, animated: false)
//        self.view.addSubview(navigationBar)
        
        
//        codeView = UIView(frame: CGRectMake(10, 85, 220, 40))
//        codeView.backgroundColor = UIColor.clearColor()
//        codeView.layer.borderWidth = 0.5
//        codeView.layer.borderColor = UIColor.lightGrayColor().CGColor
//        self.view.addSubview(codeView)
        
//        textField = UITextField(frame: CGRectMake(5, 0, 120, 40))
//        textField.keyboardType = UIKeyboardType.NumberPad
//        codeView.addSubview(textField);
        
        reSendButton = UIButton(frame: CGRectMake(0, 0, 80, verTextfield.frame.height))
        reSendButton.backgroundColor = BUTTON_COLOR
        reSendButton.setTitle("重发", forState: UIControlState.Normal)
        reSendButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        reSendButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        reSendButton.layer.borderWidth = 1;
//        reSendButton.layer.borderColor = UIColor.lightGrayColor().CGColor
        reSendButton.addTarget(self, action: Selector("resend:"), forControlEvents: UIControlEvents.TouchUpInside)
//        codeView.addSubview(reSendButton)
        reSendButton.enabled = false
        
        self.tishiLabel.text = tmpString
        self.verTextfield.rightView = reSendButton;
        self.verTextfield.clipsToBounds = true
        self.verTextfield.rightViewMode = UITextFieldViewMode.Always
        self.verTextfield.rightViewRectForBounds(CGRectMake(0, 0, 70, 40))
//        var button:UIButton = UIButton(frame: CGRectMake(20, CGRectGetMaxY(codeView.frame) + 80 , 100.0, 34.0))
//        button.backgroundColor = UIColor.blueColor()
//        button.setTitle("提交", forState: UIControlState.Normal)
//        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        button.addTarget(self, action: Selector("submit:"), forControlEvents: UIControlEvents.TouchUpInside)
//        self.view.addSubview(button)
        
//        timmer = NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:"timerFunction", userInfo:nil, repeats:true)
//        NSRunLoop.currentRunLoop().addTimer(timmer, forMode: NSRunLoopCommonModes)
        
    }
    
    /**
    开始计时
    */
    func doTimer() {
        tick = 60
        reSendButton.enabled = false
        let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFunction:", userInfo: nil, repeats:true);
        timer.fire()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.doTimer()
        verTextfield.becomeFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    func timerFunction(timer: NSTimer) {
        tick = tick - 1
        if tick <= 0 {
            reSendButton.enabled = true
            reSendButton.setTitle("重发", forState: UIControlState.Normal)
            timer.invalidate()
            return
        } else {
            reSendButton.setTitle("\(tick)", forState: UIControlState.Normal)
        }
    }
    
    /**
    重发
    */
    func resend(sender:UIButton) {
        self.showIndicatorWithContent("正在发送")
        SMS_SDK.getVerificationCodeBySMSWithPhone(phone, zone: area) { (error) -> Void in
            self.hideIndicator()
            if (error != nil) {
                  UIAlertView.showWithTitle("", message: ("状态码：\(error.errorCode) ,错误描述：\(error.errorDescription)"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
            } else {
                self.doTimer()
                self.reSendButton.enabled = false
            }
        }
        
//        self.doTimer()
//        reSendButton.enabled = false

    }
    
//    func showPwdView() {
//        var view:UIView = UIView(frame: CGRectMake(CGRectGetMinX(codeView.frame), CGRectGetMinY(codeView.frame), codeView.frame.size.width, 200))
//        view.backgroundColor = UIColor.whiteColor()
//        self.view.addSubview(view)
//        
//        pwdtextField = UITextField(frame: CGRectMake(5, 0, codeView.frame.size.width, 40))
//        pwdtextField.borderStyle = UITextBorderStyle.Line
//        pwdtextField.secureTextEntry = true
//        pwdtextField.placeholder = "请输入密码"
//        view.addSubview(pwdtextField)
//        
//        
//        var button:UIButton = UIButton(frame: CGRectMake(20, CGRectGetMaxY(pwdtextField.frame) + 80 , 100.0, 34.0))
//        button.backgroundColor = UIColor.blueColor()
//        button.setTitle("注册", forState: UIControlState.Normal)
//        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        button.addTarget(self, action: Selector("registerUser"), forControlEvents: UIControlEvents.TouchUpInside)
//        view.addSubview(button)
//        
//        pwdtextField.becomeFirstResponder()
//    }
    /**
    验证短信
    */
    @IBAction func submit(sender:UIButton) {
        
        if verTextfield.text?.characters.count != 4 {
            UIAlertView.showWithTitle("", message: ("请输入正确的验证码"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
        } else {
            
            if (self.alreadyExistAccount(phone)) {
                self.showHudWithTitle("账号已经存在")
                return
            }
//            self.showPwdView()
            
            self.showIndicatorWithContent("")
            SMS_SDK.commitVerifyCode(verTextfield.text, result: { (status) -> Void in
                self.hideIndicator()
                if status == SMS_ResponseStateSuccess {
                    self.view.endEditing(true)
                    self.performSegueWithIdentifier("EnterPasswordViewController", sender: self)
                    
                } else {
                    UIAlertView.showWithTitle("", message: ("验证码错误,请输入正确的验证码"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
                }
            })
        }
        
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier=="EnterPasswordViewController")  {
            
            var detailViewController:EnterPasswordViewController=segue.destinationViewController as! EnterPasswordViewController
            detailViewController.phone = self.phone
            
        }
        
    }
    
//    func registerUser() {
//        if count(pwdtextField.text) < 6 {
//            UIAlertView.showWithTitle("", message: ("密码必须不小于6位"), cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
//            return
//        }
//        
//
//        
//        var accountObj = AVObject(className: "AccountClass")
//        accountObj.setObject(phone, forKey: "userAccount")
//        accountObj.setObject( pwdtextField.text, forKey: "userPassword")
//        accountObj.setObject(phone, forKey: "acountName")
//        accountObj.setObject(false, forKey: "isThirdPartLogin")
//
//        self.showIndicatorWithContent("正在注册")
//
//        var ret = accountObj.save() as Bool
//
//        self.hideIndicator()
//
//        if(ret == true) {
//            //存储数据
//
//            NSUserDefaults.standardUserDefaults().setObject(phone, forKey:"userAccount")
//            NSUserDefaults.standardUserDefaults().setObject(phone, forKey:"acountName")
//            NSUserDefaults.standardUserDefaults().synchronize()
//            NSUserDefaults.standardUserDefaults().setBool(true, forKey:"isUserLoggedIn")
//            //显示注册成功信息
//
//            //self.presentViewController(myAlert, animated: true, completion: nil)
//
//            UIAlertView.showWithTitle("注册成功", message: "", cancelButtonTitle: "ok", otherButtonTitles: nil, tapBlock: nil)
//
//            if (delegate != nil) {
//                delegate.verifyCompleted()
//            }
//            //self.back()
//        }
//    }
//    func back() {
//        self.dismissViewControllerAnimated(true, completion: nil)
//    }
    
}
